<template>
  <div class="ap_manage_container flex gap-10px">
      <el-card class="flex-1">
          <template #header>
              <span>{{ t('deviceManage.device_firmware_label') }}</span>
          </template>
          <div>
              <el-form>
                  <el-form-item :label="t('deviceManage.current_device_version_label')" label-suffix=":">
                      <span>{{ deviceCurrentFirmware }}</span>
                  </el-form-item>
              </el-form>
              <div class="flex gap-10px m-b-10px">
                  <div class="global_btn" v-globalLoading="switchCpVersion">
                      <svg-icon icon-class="switch" class="table_icon"></svg-icon>
                      <span class="m-l-5px">{{ t('deviceManage.switch_firmware_label') }}</span>
                  </div>
                  <div class="global_btn" v-globalLoading="refresh">
                      <div >
                          <svg-icon icon-class="refresh" class="table_icon"
                              :class="{ 'rotate-animation': isRotating }"></svg-icon>
                      </div>
                      <span class="m-l-5px">{{ t('deviceManage.refresh_firmware_label') }}</span>
                  </div>
                  <div class="global_btn" v-globalLoading="deleteCpVersion">
                      <svg-icon icon-class="delete" class="table_icon"></svg-icon>
                      <span class="m-l-5px">{{ t('deviceManage.delete_firmware_label') }}</span>
                  </div>
              </div>
              <el-table :data="cpVersionList">
                  <el-table-column :label="t('deviceManage.choose_label')">
                      <template v-slot="{ row}">
                          <el-radio @change="getCurrentRow(row)" v-model="radio" :value="row.name"></el-radio>
                      </template>
                  </el-table-column>
                  <el-table-column :label="t('deviceManage.current_device_version_label')" prop="name"/>
                  <el-table-column :label="t('deviceManage.timestamp_label')" prop="timestamp"/>
              </el-table>
          </div>
      </el-card>
      <el-card class="flex-1">
          <template #header>
              <span>{{ t('deviceManage.local_firmware_upgrade_label') }}</span>
          </template>
          <el-form>
              <el-form-item :label="t('deviceManage.image_path_label')" label-suffix=":">
                  <div class="flex import_firmware_container w-100% gap-10px">
                      <el-input v-model="upgradeFirmwareConfig.fileName" class="m-r-10px"></el-input>
                      <div class="global_btn" style="min-width: 100px;" @click="importFirmware">               
                        <span class="m-l-5px">{{ t('deviceManage.import_firmware_label') }}</span>
                      </div>
                       <div class="global_btn" style="min-width: 100px;" v-globalLoading="uploadFirmware" >{{ t('deviceManage.upload_firmware_label') }}</div>
                      <input type="file" style="display: none;" ref="fileInputRef" @change="handleFileChange">
                  </div>
              </el-form-item>
              <el-form-item :label="t('deviceManage.upload_progress_label')" v-if="upgradeFirmwareConfig.showUploadProgress">
                    <div class="flex w-100%">
                    <el-progress 
                     class="w-80% m-r-10px"
                    :percentage="upgradeFirmwareConfig.uploadProgress"  
                    :text-inside="true" 
                    />
                    <div class="global_btn" @click="cancelUpload" >{{ t('deviceManage.cancel_upload_label') }}</div>
                    </div>
                </el-form-item>
               <el-form-item :label="t('deviceManage.upgrade_progress_label')" v-if="firmwareUpgradeConfig.showUpgradeProgress">
                  <div class="flex w-100%">
                  <el-progress 
                   class="w-80% m-r-10px"
                  :percentage="firmwareUpgradeConfig.progress"  
                  :text-inside="true" 
                  />
                  <div class="global_btn" v-globalLoading="handleUpgradeFirmware" >{{ t('deviceManage.upgrade_firmware_label') }}</div>
                  </div>          
               </el-form-item>
          </el-form>
      </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'CpManage',
})
</script>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { FirmwareManagementApi } from '@/api/firmwareManagement'
import { ElNotificationFn } from '@/utils/computedUtils'
import {OtaApi} from '@/api/ota'
import dayjs from 'dayjs'
import axios, { CancelTokenSource } from 'axios'
const props = defineProps<{
  upgradeType:string
}>()
const { t } = useI18n()
const isRotating = ref(false)
const refresh = async () => {
  isRotating.value = true
  await getCpVersionList()
  ElNotificationFn('success', t('deviceManage.refresh_firmware_success_label'))
  setTimeout(() => {
      isRotating.value = false
  }, 1000)
}
const deviceCurrentFirmware = ref('')
const cpVersionList = ref([])
const currentRow = ref('')
const radio = ref('')
async function getCpVersionList() {
  const { data } = await FirmwareManagementApi.reqGetCpVersionList()
  cpVersionList.value = data.list.map((item:any)=>{
    return {
      ...item,
      timestamp: dayjs(item.timestamp * 1000).format('YYYY-MM-DD HH:mm:ss')
    }
  })
}
async function getCurrentCpVersion() {
  const { data } = await FirmwareManagementApi.reqGetCurrentCpVersion()
  deviceCurrentFirmware.value = data.name
  radio.value = data.name
  currentRow.value = data
}
async function switchCpVersion() {
  if (!currentRow.value) {
      ElNotificationFn('warning', t('deviceManage.not_choose_label'))
  }
  await FirmwareManagementApi.reqSwitchCpVersion(currentRow.value)
   await new Promise(resolve => setTimeout(resolve, 2000))
   await getCurrentCpVersion()
  ElNotificationFn('success', t('deviceManage.switch_cp_version_success_label'))
}
async function deleteCpVersion() {
  await FirmwareManagementApi.reqDeleteCpVersion(currentRow.value)
  await getCpVersionList()
  await getCurrentCpVersion()
  ElNotificationFn('success', t('deviceManage.delete_cp_version_success_label'))
}
function getCurrentRow(row: any) {
  currentRow.value = row
}
const upgradeFirmwareConfig = ref<any>({
  file:null,
  fileName:'',
  upLoadBtnLoading:false,
  uploadProgress:0,
  showUploadProgress:false
})
function uploadProgressFn(progress:ProgressEvent){
    upgradeFirmwareConfig.value.uploadProgress = Math.round((progress.loaded / progress.total) * 100)
}
let cancelToken:CancelTokenSource | null = null
const fileInputRef = ref()
function importFirmware(){
  fileInputRef.value.click()
}
function cancelUpload(){
    if (cancelToken) {
        cancelToken.cancel()
    }
    upgradeFirmwareConfig.value.uploadProgress = 0
    upgradeFirmwareConfig.value.upLoadBtnLoading = false
    upgradeFirmwareConfig.value.showUploadProgress = false
    cancelToken = null  
}
const handleFileChange = (event: any) => {
  const file = event.target.files[0];
  upgradeFirmwareConfig.value.file = file;
  upgradeFirmwareConfig.value.fileName = file.name
};
async function uploadFirmware(){
  upgradeFirmwareConfig.value.upLoadBtnLoading = true
  upgradeFirmwareConfig.value.showUploadProgress = true
  try {
      const formData = new FormData()
      formData.append('filedata',upgradeFirmwareConfig.value.file)
      formData.append('filename',upgradeFirmwareConfig.value.fileName)
      cancelToken = axios.CancelToken.source()
      await OtaApi.uploadFile(formData,uploadProgressFn,cancelToken.token)
      ElNotificationFn('success',t('deviceManage.upload_firmware_success_label'))
      firmwareUpgradeConfig.value.showUpgradeProgress = true
  } catch (error) {
    if (axios.isCancel(error)) {
            ElNotificationFn('info',t('deviceManage.cancel_upload_label'))
        } else {
            ElNotificationFn('error',t('deviceManage.upload_firmware_failure_label'))
        }
  }finally{
      upgradeFirmwareConfig.value.upLoadBtnLoading = false
  } 
}
const firmwareUpgradeConfig = ref<any>({
  progress:0,
  upgradeBtnLoading:false,
  showUpgradeProgress:false
})
async function handleUpgradeFirmware(){
  if(!upgradeFirmwareConfig.value.fileName){
    ElNotificationFn('warning',t('deviceManage.not_choose_firmware_label'))
    return
  }
  firmwareUpgradeConfig.value.upgradeBtnLoading = true
  try {
      await OtaApi.reqUpgradeFirmwareByRaw({
          filename:upgradeFirmwareConfig.value.fileName,
          type:props.upgradeType
      })
      await new Promise(resolve => setTimeout(resolve, 5000))
      getUpgradeStatus()
  } catch (error) {
      ElNotificationFn('error',t('deviceManage.upgrade_firmware_failure_label'))
  }finally{
      firmwareUpgradeConfig.value.upgradeBtnLoading = false
  }
}
let  upgradeTimer:any = null
const getUpgradeStatus = async () => {
if (upgradeTimer) {
  clearTimeout(upgradeTimer)
}
try {
  const { data } = await OtaApi.reqGetUpgradeStatusByRaw({
  filename: upgradeFirmwareConfig.value.fileName,
  type: props.upgradeType
})
firmwareUpgradeConfig.value.progress = data.progress
switch (data.status) {
  case 'success':
    ElNotificationFn('success',t('deviceManage.upgrade_firmware_success_label'))
    await nextTick()
    firmwareUpgradeConfig.value.upgradeBtnLoading = false
    break
  case 'failed':
    ElNotificationFn('error',t('deviceManage.upgrade_firmware_failure_label'))
    await nextTick()
    firmwareUpgradeConfig.value.upgradeBtnLoading = false
    break
  default:
    upgradeTimer = setTimeout(() => {
      getUpgradeStatus()
    }, 2000)
}
} catch (error) {
  ElNotificationFn('error',t('deviceManage.upgrade_firmware_failure_label'))
}finally{
  firmwareUpgradeConfig.value.upgradeBtnLoading = false
}
}
onMounted(() => {
  getCpVersionList()
  getCurrentCpVersion()
})
onUnmounted(() => {
if (upgradeTimer) {
  clearTimeout(upgradeTimer)
  upgradeTimer = null
}
})
</script>

<style lang="scss" scoped>
@import '@/styles/input.scss';
@import '@/styles/form.scss';
@import '@/styles/table.scss';
@import '@/styles/progress.scss';
.ap_manage_container {
  .table_icon {
      width: 18px;
      height: 18px;
  }

  :deep(.el-radio__label) {
      display: none;
  }

  @keyframes rotate {
      from {
          transform: rotate(0deg);
      }

      to {
          transform: rotate(360deg);
      }
  }

  .el-card {
      background: transparent;
      color: #fff;
      border: none;
  }

  .import_firmware_container {
      .el-input {
          width: 80%;
      }
  }

  .rotate-animation {
      animation: rotate 1s linear;
  }

  :deep(.el-progress-bar__outer){
      height: 26px !important;
  }

}
</style>
